﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "CmdSetMeshTexture.h"
#include "CommandIds.h"
#include "IPickFilter.h"
#include "IPickTarget.h"
#include "InteractivePicker.h"
#include "IGraphicsNodeReference.h"
#include "IElementBasicInformation.h"
#include "IGenericElement.h"
#include "IGraphicsMaterialData.h"
#include "IGraphicsMaterial.h"
#include "GbmpFileSystem.h"
#include "CommandRegister.h"
#include "UiDocumentViewUtils.h"
#include "IUserTransaction.h"
#include "UiCommonDialog.h"
#include "IGraphicsNodeStyleAndMaterialOverride.h"
#include "IDocument.h"
#include "GcmpBuiltInCategoryUniIdentities.h"
#include "EnableCompileWarning_The_LAST_IncludeInCpp.h" 


using namespace Sample;
using namespace gcmp;

namespace
{
    class PickMeshFilter : public gcmp::IPickFilter
    {
    public:

        virtual bool AllowElement(const gcmp::ElementId& id) const override
        {
            IDocument* pDocument = UiDocumentViewUtils::GetCurrentDocument();
            DBG_WARN_AND_RETURN_FALSE_UNLESS(pDocument, L"pDocument为空", L"GDMP", L"2023-11-08");
            IGenericElement* pSelElement = quick_cast<IGenericElement>(pDocument->GetElement(id));
            if (pSelElement == nullptr)
                return false;
            IElementBasicInformation* pElementBasicInformation = pSelElement->GetBasicInformation();
            if (pElementBasicInformation == nullptr)
                return false;
            if (pElementBasicInformation->GetCategoryUid() != BuiltInCategoryUniIdentities::BICU_FORM)
                return false;
            return true;
        }

        virtual bool AllowGraphicsNode(const gcmp::IGraphicsNodeReference& nodeReference) const override
        {
            return true;
        }

        virtual bool SetPickTargetOption(gcmp::IPickTarget* pickTarget) override
        {
            DBG_WARN_AND_RETURN_FALSE_UNLESS(pickTarget, L"pickTarget为空", L"GDMP", L"2023-09-30");
            pickTarget->DisableAll();
            pickTarget->EnableGraphicsElementShape();
            return true;
        }
    };

    //创建材质数据
    OwnerPtr<IGraphicsMaterialData> CreateGraphicsMaterialData(const std::wstring& filePath)
    {
        OwnerPtr<IGraphicsMaterialData> opGraphicsMaterialData = IGraphicsMaterialData::Create();
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(opGraphicsMaterialData, L"opGraphicsMaterialData为空", L"GDMP", L"2023-09-30");
        opGraphicsMaterialData->SetAmbient(Color(255, 0, 0));
        opGraphicsMaterialData->SetDiffuse(Color(155, 0, 0));
        opGraphicsMaterialData->SetSpecular(Color(55, 0, 0));
        opGraphicsMaterialData->SetTransparency(0.3);
        opGraphicsMaterialData->SetShininess(0.5);
        opGraphicsMaterialData->SetNormalTextueFilePath(filePath);
        opGraphicsMaterialData->SetDiffuseTextueFilePath(filePath);
        opGraphicsMaterialData->SetBackDiffuseTextueFilePath(filePath);
        opGraphicsMaterialData->EnableDiffuseTexture(true);
        opGraphicsMaterialData->EnableBackDiffuseTexture(true);
        opGraphicsMaterialData->EnableNormalTexture(true);
        opGraphicsMaterialData->SetUseDoubleSideMaterial(true);
        opGraphicsMaterialData->SetDiffuseTexureScale(Vector2d(0.1, 0.1));
        opGraphicsMaterialData->SetBackDiffuseTexureScale(Vector2d(0.1, 0.1));
        opGraphicsMaterialData->SetDiffuseWrapMode(IGraphicsMaterialData::EnWrapMode::MIRROR);
        bool useAlphaTest = true;
        double alphaTestThreshold = 0.5;
        opGraphicsMaterialData->EnableAlphaTest(useAlphaTest);
        opGraphicsMaterialData->SetAlphaTestThreshold(alphaTestThreshold);
        return TransferOwnership(opGraphicsMaterialData);
    }
}


REGISTER_COMMAND(CmdSetMeshTexture)

CmdSetMeshTexture::CmdSetMeshTexture() : CommandBase(ID_CMD_TEXTURE_MESH, true)
{

}

CmdSetMeshTexture::~CmdSetMeshTexture()
{

}

bool CmdSetMeshTexture::IsEnabled() const
{
    return UiDocumentViewUtils::GetCurrentDocument() != nullptr;
}

bool CmdSetMeshTexture::IsVisible() const
{
    return UiDocumentViewUtils::GetCurrentDocument() != nullptr;
}

gcmp::OwnerPtr<gcmp::IAction> CmdSetMeshTexture::ExecuteCommand(const gcmp::CommandParameters& cmdParams)
{
    IDocument* pDocument = UiDocumentViewUtils::GetCurrentDocument();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pDocument, L"pDocument为空", L"GDMP", L"2023-09-30");

    //1.拾取mesh对象
    bool isMultiSelect = false;
    const bool isPickPointSelection = true;
    std::wstring mouseTooltip = L"选择Mesh对象";
    std::wstring statusBarTooltip = L"选择Mesh对象";
    Vector3d mousePoint;
    GraphicsNodeReferenceOwnerPtrVector meshSelections;
    OwnerPtr<PickMeshFilter> pickMeshfilter(NEW_AS_OWNER_PTR(PickMeshFilter));
    auto pickResult = InteractivePicker::Select(isMultiSelect, isPickPointSelection, TransferOwnership(pickMeshfilter), mouseTooltip, statusBarTooltip, mousePoint, meshSelections);
    if (pickResult.FinishStatus != InteractivePicker::PickerFinishStatus::Successful || meshSelections.size() != 1)
        return nullptr;

    //2.导入贴图
    std::wstring filePath = UiCommonDialog::ShowOpenFileDialog(GBMP_TR(L"打开贴图文件"), gcmp::FileSystem::GetWorkingDirPath(), L"*.jpg");
    if (filePath.empty())
        return nullptr;

    //3. 通过OverrideGraphicsMaterial对材质进行重载
    OwnerPtr<IUserTransaction> opUserTransaction = IUserTransaction::Create(pDocument, GBMP_TR(L"设置贴图"));
    //利用贴图创建材质数据
    OwnerPtr<IGraphicsMaterialData> opGraphicsMaterialData = CreateGraphicsMaterialData(filePath);
    IGraphicsMaterial* pGraphicsMaterial = IGraphicsMaterial::Create(pDocument, ElementCreationOptions::Normal, filePath);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pGraphicsMaterial, L"pGraphicsMaterial为空", L"GDMP", L"2023-09-30");
    pGraphicsMaterial->UpdateMaterialInstanceByGraphicsMaterialData(*opGraphicsMaterialData);
    auto&& brepBodyNodeReference = meshSelections[0];
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(brepBodyNodeReference, L"brepBodyNodeReference为空", L"GDMP", L"2023-09-30");
    IElement* pSelMeshElement = pDocument->GetElement(brepBodyNodeReference->GetElementId());
    gcmp::IGraphicsNodeStyleAndMaterialOverride* pIGraphicsNodeStyleAndMaterialOverride = pSelMeshElement->GetShapeGraphicsNodeStyleAndMaterialOverrideComponentFW();
    if (pIGraphicsNodeStyleAndMaterialOverride)
    {
        pIGraphicsNodeStyleAndMaterialOverride->OverrideGraphicsMaterial(pGraphicsMaterial->GetElementId());
    }
    opUserTransaction->Commit();

    return nullptr;
}